//
//  MDDeviceOperateViewController.m
//  MideaWorld_Zizhu
//
//  Created by Minus on 5/22/15.
//  Copyright (c) 2015 Minus. All rights reserved.
//

#import "MDDeviceOperateViewController.h"
#import "MDXPGApplianceApi.h"
#import "MDCreateCmdViewController.h"
#import "MDUserDefaults.h"
#import "fcCon.h"

@interface MDDeviceOperateViewController () <UITableViewDataSource, UITableViewDelegate>
{
    NSMutableArray *_deviceList;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *labelResult;

@end

@implementation MDDeviceOperateViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _deviceList = [NSMutableArray new];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (IBAction)actionGetDeviceList:(id)sender
{
    self.labelResult.text = @"正在获取设备列表...";
    
    [[MDXPGApplianceApi getInstance] getDeviceList:^(BaseMessage *baseMessage, NSArray *applianceInfos) {
        
        if ([baseMessage getCode] == 0) // 获取设备列表成功
        {
            if ([applianceInfos count] > 0)
            {
                self.labelResult.hidden = YES;
                self.tableView.hidden = NO;
                
                if (_deviceList)
                {
                    [_deviceList removeAllObjects];
                    [_deviceList addObjectsFromArray:applianceInfos];
                }
                else
                {
                    _deviceList = [NSMutableArray arrayWithArray:applianceInfos];
                }
                
                [self.tableView reloadData];
                
                for (ApplianceInfo *info in applianceInfos)
                {
                    NSLog(@"applianceID: %@", [info getApplianceId]);
                    NSLog(@"applianceSN: %@", [info getApplianceSN]);
                    NSLog(@"applianceType: %@", [info getApplianceType]);
                    NSLog(@"description: %@", [info getDes]);
                    NSLog(@"name: %@", [info getName]);
                    NSLog(@"active status: %@", @([info isActiveStatus]));
                    NSLog(@"online status: %@\n", @([info isOnlineStatus]));
                    
                }
            }
            else
            {
                self.labelResult.text = @"当前账号没有绑定过的设备";
            }
        }
        else
        {
            self.labelResult.text = [NSString stringWithFormat:@"获取设备列表失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

- (IBAction)actionLogout:(id)sender
{
    [[MDXPGApplianceApi getInstance] userLogout:^(BaseMessage *baseMessage) {
        
        if ([baseMessage getCode] == 0)
        {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        else
        {
            self.labelResult.text = [NSString stringWithFormat:@"注销失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_deviceList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"_cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    
    ApplianceInfo *info = _deviceList[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"设备ID：%@，设备SN：%@，设备名：%@", [info getApplianceId], [info getApplianceSN], [info getName]];
    
    NSString *isActive = [info isActiveStatus] ? @"已激活" : @"未激活";
    NSString *isOnline = [info isOnlineStatus] ? @"在线" : @"离线";
    
    cell.detailTextLabel.text = [NSString stringWithFormat:@"设备类型：%@，激活：%@，在线：%@", [info getApplianceType], isActive, isOnline];
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ApplianceInfo *info = _deviceList[indexPath.row];
    
    // 将选择的设备ID保存起来，操作设备时需要用到
    [MDUserDefaults sharedInstance].currentApplianceID = [info getApplianceId];
    [MDUserDefaults sharedInstance].currentAppliance = info;
    
    // 获取设备类型
    NSString *deviceType = [info getApplianceType];
    
    // 判断设备类型
    if ([deviceType equalsIgnoreCase:fcCon_DEHUMI_STR_])    // 除湿
    {
        [self performSegueWithIdentifier:@"dehumidifier" sender:nil];
    }
    else if ([deviceType equalsIgnoreCase:fcCon_HUMI_STR_]) // 加湿
    {
        [self performSegueWithIdentifier:@"humidifier" sender:nil];
    }
    else
    {
        [self performSegueWithIdentifier:@"createCommandSegue" sender:nil];
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        ApplianceInfo *info = _deviceList[indexPath.row];
        [self deleteDevice:[info getApplianceId]];
        
        [_deviceList removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

// 删除设备
- (void)deleteDevice:(NSString *)applianceID
{
    [[MDXPGApplianceApi getInstance] deleteDevice:applianceID completion:^(BaseMessage *baseMessage) {
        
        if ([baseMessage getCode] == 0)
        {
            NSLog(@"删除设备成功");
        }
        else
        {
            NSLog(@"删除设备失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]);
        }
    }];
}

@end
